//
//  ZKComposeViewController.swift
//  Weibo
//
//  Created by 郑克哥哥 on 2017/8/3.
//  Copyright © 2017年 郑克哥哥. All rights reserved.
//

import UIKit
import SVProgressHUD

let grayColor:UIColor = UIColor(white: 0.75, alpha: 1)

//发微博视图控制器
class ZKComposeViewController: UIViewController {
    //懒加载控件
    private lazy var titleLabel: UILabel = {
        
        let label = UILabel(font: 17, textColor: UIColor.black)

        
        if let name = ZKUserAccount.sharedViewModel.userAccount?.name{
            let title = "发微博\n" + name
            //把字符串转成副文本
            let attributedStr = NSMutableAttributedString(string: title)
            //获取名字范围
            let nameRange = (title as NSString).range(of: name)
            //给指定范围添加对应的副文本属性
            attributedStr.addAttributes([NSForegroundColorAttributeName:grayColor,NSFontAttributeName:UIFont.systemFont(ofSize: 14)], range: nameRange)
            //设置副文本
            label.attributedText = attributedStr
            
        }else{
                   label.text = "发微博"
            }
        
        label.numberOfLines = 0
        label.sizeToFit()
        label.textAlignment = .center
        return label
        
    }()
    
    //textView
    private lazy var textView: ZKTextView = {
        let View = ZKTextView()
        View.placeHolder = "人生无非是，快乐的时候大笑，难过的时候哭泣，接着就是继续过下去!人生无非是，快乐的时候大笑，难过的时候哭泣，接着就是继续过下去。"
        View.font = UIFont.systemFont(ofSize: 14)
        //设置代理,监听文字改变
        View.delegate = self
        View.alwaysBounceVertical = true
        return View
    }()
    
    //发送按钮
    private lazy var sendButton:UIButton = {
        let button = UIButton()
       // button.addTarget(self, action: #selector(sendWeibo), for: .touchUpInside)
        button.setBackgroundImage(UIImage(named:"common_button_orange"), for: .normal)
        button.setBackgroundImage(UIImage(named:"common_button_orange_highlighted"), for: .highlighted)
        button.setBackgroundImage(UIImage(named:"common_button_disable"), for: .disabled)
        button.setTitle("发送", for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: 15)
        button.setTitleColor(UIColor.white, for: .normal)
        button.setTitleColor(UIColor.gray, for: .disabled)
        button.size = CGSize(width: 45, height: 35)
        return button
    }()
    
    private lazy var toolBar:ComposeToolBar = ComposeToolBar()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.backgroundColor = UIColor.white
        
        
        setupUI()
    }
    
    
    private func setupUI(){
        //监听键盘frame的改变
        NotificationCenter.default.addObserver(self, selector: #selector(keyBoardframeChange(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        setupNavUI()
        view.addSubview(textView)
        view.addSubview(toolBar)
        textView.snp.makeConstraints { (make) in
            make.top.leading.trailing.equalTo(view)
            make.bottom.equalTo(toolBar.snp.top)
        }
        toolBar.snp.makeConstraints { (make) in
            make.bottom.equalTo(view)
            make.leading.trailing.equalTo(textView)
            make.height.equalTo(35)
        }
    }
    
    //设置导航栏按钮
    private func setupNavUI() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: #selector(cancel))
        //自定义titleView
        navigationItem.titleView = titleLabel
        
        //添加右侧发送按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        //默认不可用
        navigationItem.rightBarButtonItem?.isEnabled = false
        
    }
    
    //点击取消按钮
    @objc private func cancel() {
        //失去第一响应者
        textView.resignFirstResponder()
        dismiss(animated: true, completion: nil)
    }
    
    //点击发送按钮(发送微博内容)
    @objc private func sendWeibo(){
        
        //获取令牌
        let token = ZKUserAccount.sharedViewModel.accessToken!
        //获取微博内容
        let text = textView.text!
        print(token,text)
        NetworkTools.sharedTools.sendWeibo(access_token: token, status: text) { (response, error) in
            if error != nil{
                print("error\(error)")
                SVProgressHUD.showError(withStatus: "发送失败")
                return
            }
            SVProgressHUD.showSuccess(withStatus: "发送成功")
        }
        
    }
    
    ///MARK: -------监听键盘frame改变-------
    @objc private func keyBoardframeChange(noti:Notification) {
        let userInfo = noti.userInfo!
//        print(userInfo)
        //获取键盘frame
        let keyboardFrame = userInfo[UIKeyboardFrameEndUserInfoKey] as! CGRect
        print(keyboardFrame)
        //更新约束
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(view).offset(keyboardFrame.origin.y - ScreenHeight)
        }
        //执行约束动画
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
    }
}

//MARK: -------UITextViewDelegate-------
extension ZKComposeViewController: UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        //根据文本框是否有内容判断发送按钮是否可用
        navigationItem.rightBarButtonItem?.isEnabled = textView.hasText
    }
    //将要拖拽
    func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        //结束编辑失去第一响应者
        self.view.endEditing(true)
    }
    
}

